import 'package:app/api/command/index.dart';
import 'package:app/api/heart/index.dart';
import 'package:app/api/map/index.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class PointDelivery extends StatefulWidget{
  const PointDelivery({super.key});
  @override
  State<PointDelivery> createState() => _PointDeliveryState();
}

/// 点到点配送
class _PointDeliveryState extends State<PointDelivery>{

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  final FocusNode _taskEndpointFocusNode = FocusNode();

  // 车辆编码
  String _code = "";
  // 任务终点
  String _taskEndpoint = "";

  late List<dynamic> _sites;

  // 选中站点IDS
  late String _siteId;

  late bool _taskEndPointValidate = true;

  final FocusNode _firstFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      loadSites();
    });

    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  /// 提交
  void submit(){
    setState(() => _taskEndPointValidate = true);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      startRun();
    });
  }

  /// 开始运行
  void startRun(){
    Forms.validate(_formKey!).then((valid){
      if(valid){
        Command.of(context).delivery({'agvCode': _code, 'siteId': _siteId}).then((res){
          if(res.data['data']['code'] == 'success'){
            clear();
            Success.of(context).show('配送单创建成功');
          }
        });
      }
    });
  }

  void clear(){
    setState(() {
      _code = "";
      _taskEndpoint = "";
    });
  }

  void loadSites(){
    MapApi.of(context).sites().then((res) => StringUtils.isNotNull(res.data['data']) ? setState(() => _sites = res.data['data']) : null);
  }

  void onSelect(){
    Select(
      context: context,
      title: '选择任务终点',
      list: _sites,
      columnNum: 2,
      confirmClick: (selected) => setTaskEndpoint(selected),
    ).show();
  }

  void setTaskEndpoint(List selected){
    Map<String, dynamic> selectedMap = _sites[selected[0]];
    setState(() {
      _taskEndpoint = StringUtils.isNotNull(selectedMap['children']) &&
          selectedMap['children'].length > 0 ? selectedMap['name']
          + "/" + selectedMap['children'][selected[1]]['name'] : selectedMap['name'];
      _siteId = selectedMap['children'].length > 0 ?
        selectedMap['children'][selected[1]]['id'] : '';
    });
  }

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  void setValue(String key, String value){
    switch(key){
      case '_code' : _code = value;break;
      default:
        throw Exception("key error");
    }
  }

  void hideKeyBorder(){
    FocusScopeNode currentFocus = FocusScope.of(context);
    if(!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null){
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void go(path) => Navigator.pushNamed(context, path);

  /// 车辆归位
  void stop() async{
    setState(() {
      _taskEndPointValidate = false;
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      homing();
    });
  }

  /// 调用归位接口
  void homing(){
    Forms.validate(_formKey!).then((valid){
      if(valid){
        HeartApi.of(context).homing(_code).then((res){
          if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
            Success.of(context).show('车辆已归位');
            clear();
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '点到点配送'),
      body: SingleChildScrollView(
        child: GestureDetector(
          onTap: hideKeyBorder,
          child: Container(
            color: const Color.fromARGB(255, 245, 245, 245),
            child: Column(
              children: [
                Group(
                  title: '车辆操作',
                  height: 120,
                  context: context,
                  child: Menu(
                      context: context,
                      items: [
                        MenuItem(
                          icon: const Icon(Icons.call,color: Colors.white,size: 40),
                          text: "空车呼叫",
                          color: const Color.fromARGB(255, 154, 204, 109),
                          onTap: ()=>go('/call'),
                        ),
                        MenuItem(
                          icon: const Icon(Icons.car_rental, color: Colors.white,size: 40),
                          text: "托盘搭载",
                          color: const Color.fromARGB(255, 107, 200, 171),
                          onTap: ()=>go('/carrying'),
                        ),
                        MenuItem(
                          icon: const Icon(Icons.place, color: Colors.white,size: 40),
                          text: "托盘放置",
                          color: const Color.fromARGB(255, 109, 183, 234),
                          onTap: ()=>go('/place'),
                        ),
                      ]
                  ),
                ),
                Group(
                  title: '车辆信息',
                  context: context,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Forms(
                        formKey: _formKey,
                        formItem: [
                          FormItem(
                            type: 'input',
                            labelText: '车辆编号',
                            placeholder: '请扫描车辆编号',
                            focusNode: _firstFocusNode,
                            filedName: 'code',
                            iconOnTap: scan,
                            value: _code,
                            icon: const Icon(Icons.qr_code_scanner_rounded),
                            onChange: (value) => setValue('_code', value),
                            rules: const {'code': [{'required': true, 'message': '车辆编号不能为空'}]},
                          ),
                          FormItem(
                            focusNode: _taskEndpointFocusNode,
                            type: 'input',
                            labelText: '任务终点',
                            filedName: 'taskEndpoints',
                            placeholder: '请选择任务终点',
                            iconOnTap: onSelect,
                            value: _taskEndpoint,
                            onClick: onSelect,
                            validate: _taskEndPointValidate,
                            readOnly: true,
                            icon: const Icon(Icons.keyboard_arrow_right),
                            onChange: (value) => setValue(value, '_taskEndpoint'),
                            rules: const {'taskEndpoint': [{'required': true, 'message': '任务终点不能为空'}]},
                          ),
                        ],
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 10, right: 10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(top: 10, right: 10, bottom: 10),
                              child: Button(
                                label: '清空',
                                icon: Icons.delete_forever,
                                onPressed: clear,
                                fontColor: Colors.black,
                                backgroundColor: Colors.white,
                                borderColor: const Color.fromARGB(255, 133, 133, 133),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(left: 10, top: 10, bottom: 10),
                              child: Button(
                                label: ' 归位',
                                icon: Icons.edit_calendar,
                                onPressed: stop,
                                iconColor: Colors.white,
                                fontColor: Colors.white,
                                backgroundColor: const Color.fromARGB(255, 69, 228, 194),
                                borderColor: const Color.fromARGB(255, 69, 228, 194),
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width,
                  child: Padding(
                    padding: const EdgeInsets.only(top: 20, left: 20, right: 20),
                    child: Button(
                      onPressed: submit,
                      label: '开始运行',
                      height: 60,
                      fontSize: 18,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      )
    );
  }
}